package algorithm.sort;

import java.util.Arrays;

//堆排序
public class HeapSort {
    public static void main(String[] args) {
        int[] data = new int[]{-99,-6,3,78,9,40,-1,1};
//        int[] data = new int[]{19,97,1,8,9,17};
        heapSort(data,data.length);
        System.out.println(Arrays.toString(data));
    }

    public static void heapFy(int[]data,int root,int length){
        if (root>length){
            return;
        }
        int left = root*2+1;
            int right = root*2+2;
        int max = data[root];
        if (right<length && max<data[right]){
            max = data[right];
        }
        if (left<length && max<data[left]){
            max = data[left];
        }
        if (max !=data[root]){
            //如果是右孩子
            if (right<length && max == data[right]){
                data[right] = data[root];
                heapFy(data,right,length);
            }
            if (left<length && max == data[left]){
                data[left] = data[root];
                heapFy(data,left,length);
            }
            data[root] = max;
        }

    }
    public static void heapSort(int[] data,int length){
        for (int i =(length-1)/2 ;i>=0;i--){
            heapFy(data,i,length);
        }
        int temp ;

        //如果下面的循环不写，只是进行了一次大顶锥
        for (int j = length-1;j>0;j--){
             temp = data[j];
            data[j] = data[0];
            data[0] = temp;
            heapFy(data,0,j);
        }
    }
}
